package com.example.myapplication.module_common_service;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.data.CourseScore;
import com.example.myapplication.data.FeedBack;
import com.example.myapplication.data.GlobalData;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class FeedBackFragment extends Fragment {

    public static  final  int OK_ADD_FEED_BACK = 3;
    private static final int REQUEST_ADD_PAGE = 4;
    private final int GET_DATA = 1;
    private final int DEL_DATA = 2;
    private final int REFRESH = 3;
    ListView lv;
    List<FeedBack> data = new ArrayList<>();

    public FeedBackFragment() {
        // Required empty public constructor
    }    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case GET_DATA:
                    data.clear();
                    if (msg.obj!=null){
                        data.addAll((List<FeedBack>)msg.obj);
                    }
                    lv.setAdapter(new FeedBackAdapter(data,getLayoutInflater(),getContext()));

                    break;
                case DEL_DATA:
                    Toast.makeText(getContext(),"删除成功！",Toast.LENGTH_LONG).show();
                    getData();
                    break;
                case REFRESH:
                    getData();
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void getData(){
        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient okHttpClient = new OkHttpClient();

                String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
                Request request = new Request.Builder().
                        url("http://120.25.230.35:8080/feedback").addHeader("jwt", substring).get().build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response execute = call.execute();
                    if(execute.isSuccessful()){
                        Message message = new Message();
                        //把jwt传进去
                        String string = execute.body().string();
                        Gson gson = new Gson();
                        List<FeedBack> dataX = gson.fromJson(string, new TypeToken<List<FeedBack>>() {
                        }.getType());
                        message.what = GET_DATA;
                        message.obj = dataX;

                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

            Message message = new Message();
            message.what = REFRESH;
            handler.sendMessage(message);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_feed_back, container, false);

        lv = root.findViewById(R.id.lv_feedback);
        root.findViewById(R.id.btn_go_add_fd).setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(),AddFeedBackActivity.class);
            startActivityForResult(intent,REQUEST_ADD_PAGE);

        });
        getData();
        return root;
    }

    private void delFeedBack(Integer id) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient okHttpClient = new OkHttpClient();

                String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
                Request request = new Request.Builder().
                        url("http://120.25.230.35:8080/feedback?feedBackId="+id).addHeader("jwt", substring).delete().build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response execute = call.execute();
                    if(execute.isSuccessful()){
                        Message message = new Message();
                        message.what = DEL_DATA;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private class FeedBackAdapter extends BaseAdapter {
        private List<FeedBack> data;
        private LayoutInflater layoutInflater;
        private Context context;
        public FeedBackAdapter(List<FeedBack> data, LayoutInflater layoutInflater, Context context) {
            this.data = data;
            this.layoutInflater = layoutInflater;
            this.context = context;
        }

        @Override
        public int getCount() {
            return data.size() ;
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return data.get(i).getId();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            FeedBackAdapter.ViewHolder viewHolder = null;

            if (convertView == null) {
                viewHolder = new FeedBackAdapter.ViewHolder();
                //获得组件，实例化组件
                convertView = layoutInflater.inflate(R.layout.layout_for_feedbacks_display, null);
                viewHolder.title= convertView.findViewById(R.id.feedback_title);
                viewHolder.date = convertView.findViewById(R.id.feedback_date);
                viewHolder.status = convertView.findViewById(R.id.feedback_status);
                viewHolder.btnDel = convertView.findViewById(R.id.delete_term);
                viewHolder.btnDetail = convertView.findViewById(R.id.detail_term);

                viewHolder.btnDetail.setOnClickListener(view -> {
                    Intent intent = new Intent(getActivity(),DetailOfFeedBack.class);
                    intent.putExtra("feedBack",data.get(position));
                    startActivity(intent);
                });
                viewHolder.btnDel.setOnClickListener(view -> {
                    AlertDialog dialog = new AlertDialog.Builder(getContext()).
                            setPositiveButton("真的要删除吗？",((dialogInterface, i) -> {
                            delFeedBack(data.get(position).getId());
                    })).setNegativeButton("取消",((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                            })).show();
                    Button btnPos =dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                    Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                    btnPos.setTextColor(Color.RED);
                    btnNeg.setTextColor(Color.RED);
                });

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (FeedBackAdapter.ViewHolder) convertView.getTag();
            }
            //绑定数据
            viewHolder.title.setText(this.data.get(position).getTitle());
            viewHolder.date.setText(this.data.get(position).getDateTime().toString());

            if (this.data.get(position).getReply().equals("")){
                viewHolder.status.setText("未回复");
            }else{
                viewHolder.status.setText("已回复");
            }

            return convertView;
        }

        /**
         * 组件集合，对应list.xml中的控件
         *
         * @author Administrator
         */
        public final class ViewHolder {
            public TextView title;
            public TextView date;
            public TextView status;
            ImageView btnDel;
            ImageView btnDetail;
        }
    }


}